﻿using System.IO;
using System.Web;
using System.Web.UI;

namespace TSharp.Core.Web
{
    /// <summary>
    /// A generic user control rendering helper, basically you initialise the view manager and 
    /// call render to render that control, but the benifit of this version is you can access the control
    /// the view manager is rendering and can set custom properties etc.
    /// </summary>
    /// <typeparam name="T">The type of the control you are rendering</typeparam>
    public class ViewManager<T> where T : Control
    {
        #region Properties

        private readonly T _control;

        // Used as a placeholder page to render the control on.
        private readonly ControlPage _holder;

        /// <summary>
        /// Gives you access to the control you are rendering allows
        /// you to set custom properties etc.
        /// </summary>
        public T Control
        {
            get { return _control; }
        }

        #endregion

        #region Constructor

        /// <summary>
        /// Default constructor for this view manager, pass in the path for the control
        /// that this view manager is render.
        /// </summary>
        /// <param name="path"></param>
        public ViewManager(string path)
        {
            //Init the holder page
            _holder = new ControlPage();

            // Create an instance of our control
            _control = (T) _holder.LoadControl(path);


            // Add it to our holder page.
            _holder.Controls.Add(_control);
        }

        #endregion

        #region Rendering

        /// <summary>
        /// Renders the current control.
        /// </summary>
        /// <returns></returns>
        public string Render()
        {
            var sw = new StringWriter();

            // Execute the page capturing the output in the stringwriter.
            HttpContext.Current.Server.Execute(_holder, sw, false);

            // Return the output.
            return sw.ToString();
        }

        #endregion
    }


    /// <summary>
    /// 
    /// <para>by tangjingbo at 2010/3/10 9:48</para>
    /// </summary>
    public class ControlPage : Page
    {
        /// <summary>
        /// 
        /// <para>by tangjingbo at 2010/3/10 9:49</para>
        /// </summary>
        /// <param name="control">The control.</param>
        /// <exception cref="T:System.Web.HttpException">
        /// 指定的服务器控件在运行时不包含在 <see cref="T:System.Web.UI.HtmlControls.HtmlForm"/> 服务器控件的开始和结束标记之间。
        /// </exception>
        /// <exception cref="T:System.ArgumentNullException">
        /// 要验证的控件为 null。
        /// </exception>
        public override void VerifyRenderingInServerForm(Control control)
        {
            //base.VerifyRenderingInServerForm(control);
        }
    }
}